<!DOCTYPE html>
<html>
<head>
    <title>Android混合服务器</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        #messages { height: 200px; border: 1px solid #ccc; overflow-y: scroll; padding: 10px; }
        button { padding: 8px 15px; margin: 5px 0; }
    </style>
</head>
<body>
<h1>Android混合服务器</h1>
<p>HTTP服务器运行中！</p>

<h2>WebSocket测试</h2>
<div id="messages"></div>
<input type="text" id="messageInput" placeholder="输入消息">
<button onclick="sendMessage()">发送</button>

<script>
        const socket = new WebSocket("ws://192.168.0.69:8080/ws");
        const HEARTBEAT_INTERVAL = 25000; // 25秒
        let lastPong = Date.now();
        let heartbeatTimer;

        // 连接建立
        socket.onopen = function(e) {
            log("WebSocket连接已建立");
            
            // 启动心跳
            heartbeatTimer = setInterval(() => {
                if (socket.readyState === WebSocket.OPEN) {
                    socket.send(JSON.stringify({
                        type: "heartbeat",
                        time: Date.now()
                    }));
                    
                    // 检查上次响应时间
                    if (Date.now() - lastPong > HEARTBEAT_INTERVAL * 2) {
                        log("服务器无响应，重新连接...");
                        socket.close();
                        window.location.reload();
                    }
                }
            }, HEARTBEAT_INTERVAL);
        };

        // 收到消息
        socket.onmessage = function(event) {

            log("收到: " + event.data);
        };

        // 连接关闭
        socket.onclose = function(event) {
            log(`连接关闭: ${event.code} ${event.reason}`);
            clearInterval(heartbeatTimer);
            
            // 3秒后重连
            setTimeout(() => window.location.reload(), 3000);
        };

        // 错误处理
        socket.onerror = function(error) {
            log("WebSocket错误: " + error.message);
        };

        // 发送消息
        function sendMessage() {
            const input = document.getElementById("messageInput");
            const message = input.value;
            
            if (message && socket.readyState === WebSocket.OPEN) {
                socket.send(message);
                log("发送: " + message);
                input.value = "";
            }
        }

        // 日志显示
        function log(message) {
            const messagesDiv = document.getElementById("messages");
            messagesDiv.innerHTML += message + "<br>";
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }
    </script>
</body>
</html>